import { TSBuffer } from "tsbuffer";
import { MacroDefine } from "../../Support/Share/Global/MacroDefine";
import { ITSBufferProto } from "../Object/TSBufferObject";
import { TSBufferUtil } from "../../Support/Share/TSBuffer/TSBufferUtil";
import { GetTypeOf } from "../../Decorator/Decorator";
import { IResponse } from "../../Codes/Model/Share/Module/Message/IMessage";

export class TSBufferHelper {

    public static Serialize(type: string, stream: Buffer) {
        let tsb = new TSBuffer(MacroDefine.GameProto as ITSBufferProto);
        let sid = TSBufferUtil.Type2SchemaId(type);
        let tData = tsb.encode(stream, sid);
        if (!tData.isSucc) {
            throw new Error(tData.errMsg);
        }
        return tData.buf;
    }

    public static Deserialize(type: string, stream: Buffer) {
        let tsb = new TSBuffer(MacroDefine.GameProto as ITSBufferProto);
        let sid = TSBufferUtil.Type2SchemaId(type);
        let parent = TSBufferUtil.Type2Parent(type);
        let tData = tsb.decode(stream, sid);
        let message = <any>tData.value;
        message.Type = type;
        message.Parent = parent;
        return message;
    }

    public static WrapMessage(message: Object) {
        let type = GetTypeOf(message);
        let parent = TSBufferUtil.Type2Parent(type);
        (<any>message).Type = type;
        (<any>message).Parent = parent;
        return message;
    }

    public static PackMessage<T extends IResponse>(clazz: typeof IResponse, message: Object): T {
        let type = GetTypeOf(clazz);
        let parent = TSBufferUtil.Type2Parent(type);
        (<any>message).Type = type;
        (<any>message).Parent = parent;
        return message as T;
    }

}